<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true">
            <el-form-item label="用餐地点" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入食堂名称" clearable size="small"
                    @keyup.enter.native="handleQuery" maxlength="20"  show-word-limit />
            </el-form-item>
            <el-form-item label="所属单位" prop="deptId">
                <treeselect v-model="queryParams.deptId" :options="deptOptions" :normalizer="normalizer"
                    :show-count="true" placeholder="请选择所属单位" style="width: 200px" 
                    @input="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" @change="handleQuery">
                    <el-option v-for="(item, index) in statusList" :key="index" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8" style="margin-bottom: 20px;">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['system:canteen:add']">添加用餐地点</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple || !canDelete" @click="handleDelete"
                    v-hasPermi="['system:canteen:remove']">删除</el-button>
            </el-col> -->
        </el-row>

        <el-table v-loading="loading" :data="canteenList" @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <!-- <el-table-column label="编号" align="center" prop="id" /> -->
            <el-table-column label="序号" align="center" type="index" width="50" />
            <el-table-column label="用餐地点" align="left" prop="name" show-overflow-tooltip />
            <el-table-column label="所属单位" align="left" prop="deptName" show-overflow-tooltip />
            <el-table-column label="地址" align="left" prop="address" min-width="120" show-overflow-tooltip />
            <el-table-column label="备注说明" align="left" prop="remark" min-width="120" show-overflow-tooltip />
            <el-table-column label="状态" align="center" prop="status" width="100">
                <template slot-scope="scope">
                    <el-switch 
                        v-model="scope.row.tempStatus"
                        active-value="0" 
                        inactive-value="1"
                        :disabled="scope.row.switchLoading"
                        @change="handleStatusChange(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="200">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-qrcode" @click="handleQrCode(scope.row)"
                        v-hasPermi="['system:canteen:qrCode']">食堂二维码</el-button>
                    <template v-if="scope.row.status === '1'">
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                            v-hasPermi="['system:canteen:edit']">修改</el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                            v-hasPermi="['system:canteen:remove']">删除</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改食堂弹窗 -->
        <CanteenDialog ref="canteenDialog" @refresh="getList" />

        <!-- 二维码弹窗 -->
        <el-dialog :visible.sync="qrCodeVisible" v-if="qrCodeVisible" :title="deptName + '/' + shitangName + '二维码'"  append-to-body>
            <div style="text-align: center;" :title="imgUrl + qrCode">
                <!-- {{ imgUrl + qrCode }} -->
                <el-image v-if="qrCode" :src="imgUrl + qrCode" style="width: 336px; height: 434px;" 
                    :preview-src-list="[imgUrl + qrCode]" />
                <div class="qr-save-btn">
                    <el-button type="primary" size="small" @click="handleSaveQrCode">保存二维码</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listCanteen, delCanteen, changeStatus, getQrCode } from "@/api/yongcanjiaofei/yongcandidian";
import { treeselect as deptTreeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import CanteenDialog from "./dialog.vue";

export default {
    name: "",
    components: { Treeselect, CanteenDialog },
    data() {
        return {
            // 图片服务器地址
            imgUrl: process.env.VUE_APP_IMG_API,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 食堂表格数据
            canteenList: [],
            // 状态数据字典
            statusList: [
                { label: '启用', value: '0' },
                { label: '停用', value: '1' }
            ],
            // 部门树选项
            deptOptions: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: undefined,
                deptId: undefined,
                status: undefined
            },
            qrCodeVisible: false,
            qrCode: '',
            shitangName: '',
            deptName: '',
            // 选中数据是否可删除
            canDelete: false,
            // 当前正在切换状态的食堂ID
            switchingId: null,
        };
    },
    created() {
        this.getList();
        this.getDeptTree();
    },
    methods: {
        /** 获取部门树 */
        getDeptTree() {
            deptTreeselect().then(response => {
                this.deptOptions = response.data;
            });
        },
        /** 转换部门数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.id || node.deptId,
                label: node.label || node.deptName,
                children: node.children
            };
        },
        /** 查询食堂列表 */
        getList() {
            this.loading = true;
            listCanteen(this.queryParams).then(response => {
                // 为每个食堂添加临时状态和loading属性
                this.canteenList = response.rows.map(item => {
                    this.$set(item, 'switchLoading', false);
                    this.$set(item, 'tempStatus', item.status);
                    return item;
                });
                this.total = response.total;
                this.loading = false;
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.queryParams.deptId = undefined;
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.$refs.canteenDialog.show();
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.$refs.canteenDialog.show(row);
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除？').then(() => {
                return delCanteen(ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(() => {
             });
        },
        /** 状态修改 */
        handleStatusChange(row) {
            if (row.switchLoading) return;
            
            // 还原状态，等待接口确认
            row.tempStatus = row.status;
            
            // 当前是启用状态，要进行停用操作
            if (row.status === '0') {
                this.$confirm('确认是否停用，停用后将暂停该用餐地点的缴费服务', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 设置loading状态
                    this.$set(row, 'switchLoading', true);
                    return changeStatus(row.id);
                }).then(response => {
                    // 成功后改变状态
                    row.status = '1';
                    row.tempStatus = '1';
                    this.msgSuccess("已停用");
                }).catch(err => {
                    // 失败时保持原状态
                    row.tempStatus = row.status;
                    if (err !== 'cancel') {
                        this.msgError('操作失败');
                    }
                }).finally(() => {
                    // 清除loading状态
                    this.$set(row, 'switchLoading', false);
                });
            } else {
                // 当前是停用状态，要进行启用操作
                this.$confirm('确认启用此数据？', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 设置loading状态
                    this.$set(row, 'switchLoading', true);
                    return changeStatus(row.id);
                }).then(response => {
                    // 成功后改变状态
                    row.status = '0';
                    row.tempStatus = '0';
                    this.msgSuccess("已启用");
                }).catch(err => {
                    // 失败时保持原状态
                    row.tempStatus = row.status;
                    if (err !== 'cancel') {
                        this.msgError('操作失败');
                    }
                }).finally(() => {
                    // 清除loading状态
                    this.$set(row, 'switchLoading', false);
                });
            }
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
            // 检查选中的数据是否都是停用状态
            this.canDelete = selection.length > 0 && selection.every(item => item.status === '1');
        },
        // 获取食堂二维码
        handleQrCode(row) {
            let data = {
                id: row.id,
                url: 'pages/meal/payment/payment?id=' + row.id
            }
            this.shitangName = row.name;
            this.deptName = row.deptName;
            getQrCode(data).then(response => {
                this.qrCode = response.msg;
                this.qrCodeVisible = true;
            });
        },
        // 保存二维码到本地
        handleSaveQrCode() {
            const image = new Image();
            image.crossOrigin = "anonymous";
            image.src = this.imgUrl + this.qrCode;
            image.onload = () => {
                const canvas = document.createElement("canvas");
                canvas.width = image.width;
                canvas.height = image.height;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(image, 0, 0);
                
                const link = document.createElement("a");
                link.download =  `${this.deptName}/${this.shitangName}食堂二维码.png`;
                link.href = canvas.toDataURL("image/png");
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            };
        }
    }
};
</script>

<style lang="scss" scoped>
.el-table .cell {
    white-space: pre-line;
}

/* 处理空值的显示 */
.el-table td.el-table__cell div:empty::before {
    content: '--';
    color: #909399;
}

/* 二维码弹窗样式 */
::v-deep .el-dialog__body {
    padding: 20px;
}

.qr-save-btn {
    margin-top: 15px;
}

/* 状态按钮样式 */
.el-button.is-disabled {
    opacity: 0.8;
    cursor: not-allowed;
}

/* switch开关在loading时的样式 */
::v-deep .el-switch.is-disabled {
    opacity: 1;
    .el-switch__core {
        cursor: not-allowed;
        opacity: 0.8;
    }
}

/* 调整treeselect组件高度 */
::v-deep .vue-treeselect__control {
    height: 32px;
    line-height: 32px;
}

::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
    line-height: 32px;
}
</style>